package com.itx.gatewayx.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itx.gatewayx.domain.ChatMessage;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 * 聊天消息Mapper接口
 *
 * @author itx
 */
@Mapper
public interface ChatMessageMapper extends BaseMapper<ChatMessage> {
    
    /**
     * 分页查询聊天历史
     * 
     * @param page 分页参数
     * @param chatId 会话ID
     * @return 分页消息信息
     */
    @Select({
        "SELECT * FROM chat_message ",
        "WHERE chat_id = #{chatId} AND del_flag = 0 ",
        "ORDER BY create_time DESC"
    })
    IPage<ChatMessage> selectMessagePage(Page<ChatMessage> page, @Param("chatId") Long chatId);
    
    /**
     * 标记消息为已读
     * 
     * @param chatId 会话ID
     * @param receiverId 接收者ID
     * @return 影响行数
     */
    @Update({
        "UPDATE chat_message SET status = 1 ",
        "WHERE chat_id = #{chatId} AND sender_id != #{receiverId} AND status = 0"
    })
    int markMessagesAsRead(@Param("chatId") Long chatId, @Param("receiverId") Long receiverId);
    
    /**
     * 查询未读消息数
     * 
     * @param chatId 会话ID
     * @param receiverId 接收者ID
     * @return 未读消息数
     */
    @Select({
        "SELECT COUNT(*) FROM chat_message ",
        "WHERE chat_id = #{chatId} AND sender_id != #{receiverId} AND status = 0 AND del_flag = 0"
    })
    int countUnreadMessages(@Param("chatId") Long chatId, @Param("receiverId") Long receiverId);
} 